﻿using jinmaMesProxy.Model;
using System.Reflection;
using System.Text;

namespace jinmaMesProxy.DataAccess
{
    public class ErpDocQuery<TBase> where TBase : new()
    {
        private string SelectSql<T>()
        {
            var table = typeof(T).GetCustomAttribute<MyTableNameAttribute>()!.TableName;
            StringBuilder sb = new StringBuilder();
            var ps = typeof(T).GetProperties();
            foreach (var p in ps)
            {
                var att = p.GetCustomAttribute<MyColumnNameAttribute>();
                if (att == null) continue;
                sb.Append(att.ColumnName + ",");
            }
            sb.Remove(sb.Length - 1, 1);
            return $"SELECT {sb.ToString()} FROM {table} AS T WHERE 1=1 ";
        }

        public List<TBase> Query(string where,params KeyValuePair<string,object>[] p)
        {
            ErpDbInstance erpDbInstance = ServiceLoader.GetService<ErpDbInstance>();
            List<TBase> result = new List<TBase>();
            var baseSql = SelectSql<TBase>() + where;
            var ps = typeof(TBase).GetProperties();
            using (var cmd = erpDbInstance.MakeQueryCommand(baseSql,p))
            {
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        TBase r = new TBase();
                        foreach (var pi in ps)
                        {
                            Utils.SetVouchFromReader(r, pi, reader);
                        }
                        result.Add(r);
                    }
                }
            }
            return result;
        }
    }
}
